use reqwest::Client;
use serde_json::json;
use crate::error::{AppError, AppResult};

pub struct WeChatService {
    client: Client,
    webhook_url: String,
}

impl WeChatService {
    pub fn new(webhook_url: String) -> Self {
        Self {
            client: Client::new(),
            webhook_url,
        }
    }
    
    /// 发送文本消息到企业微信群
    pub async fn send_text_message(&self, content: &str) -> AppResult<()> {
        let body = json!({
            "msgtype": "text",
            "text": {
                "content": content
            }
        });
        
        let response = self
            .client
            .post(&self.webhook_url)
            .json(&body)
            .send()
            .await
            .map_err(|e| AppError::WeChatError(format!("Failed to send message: {}", e)))?;
        
        if !response.status().is_success() {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            return Err(AppError::WeChatError(format!(
                "WeChat API returned error {}: {}",
                status, error_text
            )));
        }
        
        Ok(())
    }
    
    /// 发送提醒消息
    /// 参数:
    /// - user_name: 用户名称，用于 @ 用户
    /// - description: 直接发送给用户的提醒内容（已包含情绪价值）
    pub async fn send_reminder(&self, user_name: &str, description: &str) -> AppResult<()> {
        // 获取中国时间 (UTC+8)
        let china_time = chrono::Utc::now() + chrono::Duration::hours(8);
        let message = format!(
            "⏰ 提醒通知\n\n@{} \n\n{}\n\n时间: {} CST",
            user_name,
            description,
            china_time.format("%Y-%m-%d %H:%M:%S")
        );
        
        self.send_text_message(&message).await
    }
}
